<template>
  <div class="product-list-page">
    <div class="page-header">
      <h1>产品列表</h1>
    </div>
    
    <div class="content-card">
      <!-- 操作按钮区域 -->
      <div class="button-group">
        <el-button type="danger" icon="el-icon-warning" @click="handleBatchToggleDisable">
          批量禁/反禁用
        </el-button>
        <el-button type="primary" icon="el-icon-plus" @click="showAddDialog">
          新增产品
        </el-button>
      </div>

      <!-- 产品列表表格 -->
      <el-table 
        :data="productList" 
        v-loading="loading" 
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="index" label="编号" width="80">
          <template slot-scope="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="serialNumber" label="产品编号" width="120">
          <template slot-scope="scope">
            <el-tag type="info" size="small">{{ scope.row.serialNumber }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="shoeName" label="产品名称" width="150">
          <template slot-scope="scope">
            <span class="product-name">{{ scope.row.shoeName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="原价" width="120">
          <template slot-scope="scope">
            <span class="price">¥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="discountedPrice" label="折扣价" width="120">
          <template slot-scope="scope">
            <span class="discounted-price" v-if="scope.row.discountedPrice">
              ¥{{ scope.row.discountedPrice }}
            </span>
            <span class="no-discount" v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="brand" label="品牌" width="120">
          <template slot-scope="scope">
            <span class="brand-name">{{ scope.row.brand?.brandName || '无品牌' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="shoeType" label="类型" width="120">
          <template slot-scope="scope">
            <span class="type-name">{{ scope.row.shoeType?.typeName || '未分类' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="color" label="颜色" width="100">
          <template slot-scope="scope">
            <span class="color-name">{{ scope.row.color?.colorName || '无颜色' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="origin" label="产地" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.origin }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="100">
          <template slot-scope="scope">
            <el-tag :type="getGenderTagType(scope.row.gender)" size="small">
              {{ scope.row.gender }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalSales" label="销量" width="100">
          <template slot-scope="scope">
            <span class="sales">{{ scope.row.totalSales }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="points" label="积分" width="100">
          <template slot-scope="scope">
            <span class="points">{{ scope.row.points }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="shoeStatus" label="状态" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.shoeStatus"
              :active-value="1"
              :inactive-value="0"
              @change="toggleProductStatus(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="showEditDialog(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="mini" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </div>

    <!-- 新增产品弹窗 -->
    <el-dialog 
      title="新增产品" 
      :visible.sync="addDialogVisible" 
      width="800px" 
      @close="resetAddForm"
      :before-close="handleCloseAddDialog"
    >
      <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品类型" prop="shoeType">
              <el-select v-model="addForm.shoeType" placeholder="请选择产品类型" style="width: 100%">
                <el-option
                  v-for="type in typeList"
                  :key="type.typeId"
                  :label="type.typeName"
                  :value="type.typeId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-select v-model="addForm.brand" placeholder="请选择品牌" style="width: 100%">
                <el-option
                  v-for="brand in brandList"
                  :key="brand.brandId"
                  :label="brand.brandName || '无品牌'"
                  :value="brand.brandId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="shoeName">
              <el-input v-model="addForm.shoeName" placeholder="请输入产品名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品编号" prop="serialNumber">
              <el-input v-model="addForm.serialNumber" placeholder="请输入产品编号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="原价" prop="price">
              <el-input-number v-model="addForm.price" :min="0" :precision="2" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="折扣价" prop="discountedPrice">
              <el-input-number v-model="addForm.discountedPrice" :min="0" :precision="2" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上市时间" prop="releaseDate">
              <el-date-picker
                v-model="addForm.releaseDate"
                type="date"
                placeholder="选择上市时间"
                style="width: 100%"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产地" prop="origin">
              <el-input v-model="addForm.origin" placeholder="请输入产地"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="addForm.gender" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
                <el-option label="男女" value="男女"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="颜色" prop="color">
              <el-select v-model="addForm.color" placeholder="请选择颜色" style="width: 100%">
                <el-option
                  v-for="color in colorList"
                  :key="color.colorId"
                  :label="color.colorName"
                  :value="color.colorId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="累计销售" prop="totalSales">
              <el-input-number v-model="addForm.totalSales" :min="0" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单品积分" prop="points">
              <el-input-number v-model="addForm.points" :min="0" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="禁用状态" prop="shoeStatus">
              <el-switch
                v-model="addForm.shoeStatus"
                :active-value="1"
                :inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              ></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图片上传">
              <el-upload
                class="upload-demo"
                action="#"
                :show-file-list="false"
                :before-upload="handleImageUpload"
                accept="image/*"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
              <!-- 多图片显示区域 -->
              <div class="image-preview-container">
                <div 
                  v-for="(image, index) in addForm.imageUrls" 
                  :key="index" 
                  class="image-preview-item"
                >
                  <img :src="'http://localhost:8083/image/' + image" class="preview-image" />
                  <div class="image-close-btn" @click="removeImage(index, 'add')">
                    <i class="el-icon-close"></i>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="商品描述" prop="description">
          <el-input type="textarea" v-model="addForm.description" placeholder="请输入商品描述" :rows="3"></el-input>
        </el-form-item>

        <el-form-item label="详细信息" prop="detailInfo">
          <el-input type="textarea" v-model="addForm.detailInfo" placeholder="请输入详细信息" :rows="3"></el-input>
        </el-form-item>

        <!-- 尺寸和库存 -->
        <el-form-item label="尺寸库存">
          <div class="size-stock-container">
            <div 
              v-for="size in sizeList" 
              :key="size.sizeId" 
              class="size-stock-item"
            >
              <span class="size-label">尺码 {{ size.sizeNumber }}:</span>
              <el-input-number 
                v-model="sizeStock[size.sizeId]" 
                :min="0" 
                :max="9999"
                size="mini"
                style="width: 100px"
                placeholder="库存"
                controls-position="right"
              ></el-input-number>
            </div>
          </div>
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCloseAddDialog">取 消</el-button>
        <el-button type="primary" @click="handleAddProduct" :loading="addLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑弹窗模板，放在新增弹窗下方 -->
    <el-dialog
      title="编辑产品"
      :visible.sync="editDialogVisible"
      width="800px"
      :before-close="handleCloseEditDialog"
    >
      <el-form :model="editForm" :rules="addFormRules" ref="editForm" label-width="100px" v-loading="editLoading">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品类型" prop="shoeType">
              <el-select v-model="editForm.shoeType" placeholder="请选择产品类型" style="width: 100%">
                <el-option v-for="type in typeList" :key="type.typeId" :label="type.typeName" :value="type.typeId"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-select v-model="editForm.brand" placeholder="请选择品牌" style="width: 100%">
                <el-option v-for="brand in brandList" :key="brand.brandId" :label="brand.brandName || '无品牌'" :value="brand.brandId"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="shoeName">
              <el-input v-model="editForm.shoeName" placeholder="请输入产品名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品编号" prop="serialNumber">
              <el-input v-model="editForm.serialNumber" placeholder="请输入产品编号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="原价" prop="price">
              <el-input-number v-model="editForm.price" :min="0" :precision="2" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="折扣价" prop="discountedPrice">
              <el-input-number v-model="editForm.discountedPrice" :min="0" :precision="2" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上市时间" prop="releaseDate">
              <el-date-picker
                v-model="editForm.releaseDate"
                type="date"
                placeholder="选择上市时间"
                style="width: 100%"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产地" prop="origin">
              <el-input v-model="editForm.origin" placeholder="请输入产地"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="editForm.gender" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
                <el-option label="男女" value="男女"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="颜色" prop="color">
              <el-select v-model="editForm.color" placeholder="请选择颜色" style="width: 100%">
                <el-option v-for="color in colorList" :key="color.colorId" :label="color.colorName" :value="color.colorId"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="累计销售" prop="totalSales">
              <el-input-number v-model="editForm.totalSales" :min="0" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单品积分" prop="points">
              <el-input-number v-model="editForm.points" :min="0" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="禁用状态" prop="shoeStatus">
              <el-switch
                v-model="editForm.shoeStatus"
                :active-value="1"
                :inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              ></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图片上传">
              <el-upload
                class="upload-demo"
                action="#"
                :show-file-list="false"
                :before-upload="handleEditImageUpload"
                accept="image/*"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
              <!-- 多图片显示区域 -->
              <div class="image-preview-container">
                <div 
                  v-for="(image, index) in editForm.imageUrls" 
                  :key="index" 
                  class="image-preview-item"
                >
                  <img :src="'http://localhost:8083/image/' + image" class="preview-image" />
                  <div class="image-close-btn" @click="removeImage(index, 'edit')">
                    <i class="el-icon-close"></i>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品描述" prop="description">
          <el-input type="textarea" v-model="editForm.description" placeholder="请输入商品描述" :rows="3"></el-input>
        </el-form-item>
        <el-form-item label="详细信息" prop="detailInfo">
          <el-input type="textarea" v-model="editForm.detailInfo" placeholder="请输入详细信息" :rows="3"></el-input>
        </el-form-item>
        <el-form-item label="尺寸库存">
          <div class="size-stock-container">
            <div v-for="size in sizeList" :key="size.sizeId" class="size-stock-item">
              <span class="size-label">尺码 {{ size.sizeNumber }}:</span>
              <el-input-number
                v-model="editSizeStock[size.sizeId]"
                :min="0"
                :max="9999"
                size="mini"
                style="width: 100px"
                placeholder="库存"
                controls-position="right"
              ></el-input-number>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCloseEditDialog">取 消</el-button>
        <el-button type="primary" @click="handleEditProduct" :loading="editLoading">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'ProductList',
  data() {
    return {
      // 产品列表数据
      productList: [],
      selectedProducts: [],
      loading: false,
      currentPage: 1,
      pageSize: 5,
      total: 0,

      // 新增弹窗数据
      addDialogVisible: false,
      addLoading: false,
      addForm: {
        shoeType: null,
        brand: null,
        color: null,
        serialNumber: '',
        shoeName: '',
        price: 0,
        discountedPrice: 0,
        releaseDate: '',
        origin: '',
        gender: '',
        description: '',
        totalSales: 0,
        detailInfo: '',
        points: 0,
        shoeStatus: 1,
        imageUrl: '',
        imageUrls: [] // 新增多图片上传
      },
      addFormRules: {
        shoeName: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        serialNumber: [
          { required: true, message: '请输入产品编号', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入原价', trigger: 'blur' }
        ],
        shoeType: [
          { required: true, message: '请选择产品类型', trigger: 'change' }
        ],
        brand: [
          { required: true, message: '请选择品牌', trigger: 'change' }
        ],
        color: [
          { required: true, message: '请选择颜色', trigger: 'change' }
        ]
      },

      // 下拉选项数据
      typeList: [],
      brandList: [],
      colorList: [],
      sizeList: [],
      sizeStock: {}, // 存储每个尺寸的库存

      // 编辑弹窗数据
      editDialogVisible: false,
      editLoading: false,
      editForm: {
        shoeType: null,
        brand: null,
        color: null,
        serialNumber: '',
        shoeName: '',
        price: 0,
        discountedPrice: 0,
        releaseDate: '',
        origin: '',
        gender: '',
        description: '',
        totalSales: 0,
        detailInfo: '',
        points: 0,
        shoeStatus: 1,
        imageUrl: '',
        imageUrls: [] // 新增多图片上传
      },
      editSizeStock: {},
      editShoeId: null,
    }
  },
  mounted() {
    this.fetchProductList()
  },
  methods: {
    // 获取产品列表
    async fetchProductList() {
      this.loading = true
      try {
        const response = await axios.get('/api/shoe/pageList', {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize
          }
        })
        
        if (response.data.code === 200) {
          this.productList = response.data.data.list
          this.total = response.data.data.total
        } else {
          this.$message.error(response.data.msg || '获取产品列表失败')
        }
      } catch (error) {
        console.error('获取产品列表失败:', error)
        this.$message.error('获取产品列表失败')
      } finally {
        this.loading = false
      }
    },

    // 分页处理
    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchProductList()
    },
    
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.fetchProductList()
    },

    // 选择处理
    handleSelectionChange(selection) {
      this.selectedProducts = selection
    },

    // 批量禁用/启用
    async handleBatchToggleDisable() {
      if (this.selectedProducts.length === 0) {
        this.$message.warning('请先选择要操作的产品')
        return
      }

      // 检查所有选中产品的状态是否一致
      const firstStatus = this.selectedProducts[0].shoeStatus
      const allSameStatus = this.selectedProducts.every(product => product.shoeStatus === firstStatus)
      
      if (!allSameStatus) {
        this.$message.warning('请选择状态相同的产品进行批量操作')
        return
      }

      const newStatus = firstStatus === 1 ? 0 : 1
      const statusText = newStatus === 1 ? '启用' : '禁用'

      try {
        await this.$confirm(`确定要批量${statusText}选中的产品吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 这里需要调用批量更新接口
        // const updatePromises = this.selectedProducts.map(product => {
        //   return axios.post('/api/shoe/updateStatus', {
        //     id: product.shoeId,
        //     status: newStatus
        //   })
        // })
        // await Promise.all(updatePromises)

        this.$message.success(`批量${statusText}成功`)
        this.fetchProductList()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(`批量${statusText}失败`)
        }
      }
    },

    // 切换单个产品状态
    async toggleProductStatus(product) {
      try {
        // 这里需要调用更新状态接口
        // const response = await axios.post('/api/shoe/updateStatus', {
        //   id: product.shoeId,
        //   status: product.shoeStatus
        // })
        
        this.$message.success('状态更新成功')
      } catch (error) {
        // 如果更新失败，恢复原状态
        product.shoeStatus = product.shoeStatus === 1 ? 0 : 1
        this.$message.error('状态更新失败')
      }
    },

    // 显示新增弹窗
    async showAddDialog() {
      this.addDialogVisible = true
      // 获取所有下拉选项数据
      await this.fetchAllOptions()
      // 初始化尺寸库存对象
      this.initSizeStock()
    },

    // 获取所有下拉选项
    async fetchAllOptions() {
      try {
        // 并行获取所有选项数据
        const [typeResponse, brandResponse, colorResponse, sizeResponse] = await Promise.all([
          axios.get('/api/shoeType/getAll'),
          axios.get('/api/brand/getAll'),
          axios.get('/api/color/getAll'),
          axios.get('/api/shoeSize/getAll')
        ])

        if (typeResponse.data.code === 200) {
          this.typeList = typeResponse.data.data
        }
        
        if (brandResponse.data.code === 200) {
          this.brandList = brandResponse.data.data
        }
        
        if (colorResponse.data.code === 200) {
          this.colorList = colorResponse.data.data
        }
        
        if (sizeResponse.data.code === 200) {
          this.sizeList = sizeResponse.data.data
        }
      } catch (error) {
        console.error('获取选项数据失败:', error)
        this.$message.error('获取选项数据失败')
      }
    },

    // 初始化尺寸库存对象
    initSizeStock() {
      this.sizeStock = {}
      this.sizeList.forEach(size => {
        this.$set(this.sizeStock, size.sizeId, 0)
      })
    },

    // 图片上传处理
    async handleImageUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt500K = file.size / 1024 < 500

      if (!isImage) {
        this.$message.error('上传文件只能是图片格式!')
        return false
      }
      if (!isLt500K) {
        this.$message.error('上传图片大小不能超过 500KB!')
        return false
      }

      try {
        const formData = new FormData()
        formData.append('flimage', file)
        
        const response = await axios.post('/api/uploadImage', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        
        if (response.data.code === 200) {
          // 只保存文件名，不保存完整URL
          this.addForm.imageUrls.push(response.data.data)
          console.log('新增弹窗图片上传成功，当前图片数组:', this.addForm.imageUrls)
          this.$message.success('图片上传成功')
        } else {
          this.$message.error(response.data.msg || '图片上传失败')
        }
      } catch (error) {
        console.error('图片上传失败:', error)
        this.$message.error('图片上传失败')
      }
      
      return false // 阻止自动上传
    },

    // 新增产品
    async handleAddProduct() {
      try {
        await this.$refs.addForm.validate()
        this.addLoading = true

        // 构建图片数据
        const shoeImages = this.addForm.imageUrls && this.addForm.imageUrls.length > 0 
          ? this.addForm.imageUrls.map((imageUrl) => ({
              imageId: 0,
              imageUrl: imageUrl, // 直接使用文件名
              shoeId: 0
            }))
          : []

        console.log('新增产品时的图片数据:', this.addForm.imageUrls)
        console.log('构建的shoeImages:', shoeImages)

        // 构建请求数据
        const requestData = {
          brand: this.brandList.find(b => b.brandId === this.addForm.brand) || {
            brandGender: "",
            brandId: 0,
            brandName: "",
            brandRemark: "",
            brandStatus: 0
          },
          color: this.colorList.find(c => c.colorId === this.addForm.color) || {
            colorId: 0,
            colorName: "",
            colorRemark: "",
            colorStatus: 0
          },
          description: this.addForm.description,
          detailInfo: this.addForm.detailInfo,
          discountedPrice: this.addForm.discountedPrice,
          gender: this.addForm.gender,
          imageUrl: this.addForm.imageUrls.length > 0 ? this.addForm.imageUrls[0] : '',
          inventoryList: this.sizeList.map(size => ({
            quantity: this.sizeStock[size.sizeId] || 0,
            shoeId: 0,
            sizeId: size.sizeId
          })),
          origin: this.addForm.origin,
          points: this.addForm.points,
          price: this.addForm.price,
          releaseDate: this.addForm.releaseDate,
          serialNumber: this.addForm.serialNumber,
          shoeId: 0,
          shoeImages: shoeImages,
          shoeName: this.addForm.shoeName,
          shoeStatus: this.addForm.shoeStatus,
          shoeType: this.typeList.find(t => t.typeId === this.addForm.shoeType) || {
            typeId: 0,
            typeName: "",
            typeRemark: "",
            typeStatus: 0
          },
          totalSales: this.addForm.totalSales
        }

        // 调用新增产品接口
        const response = await axios.post('/api/shoe/add', requestData)
        
        if (response.data.code === 200) {
          this.$message.success('新增产品成功')
          this.addDialogVisible = false
          this.fetchProductList()
        } else {
          this.$message.error(response.data.msg || '新增产品失败')
        }
      } catch (error) {
        if (error !== false) { // 表单验证失败不显示错误
          this.$message.error('新增产品失败')
        }
      } finally {
        this.addLoading = false
      }
    },

    // 显示编辑弹窗
    async showEditDialog(product) {
      this.editDialogVisible = true
      this.editLoading = true
      this.editShoeId = product.shoeId
      await this.fetchAllOptions()
      const res = await axios.get('/api/shoe/getById', { params: { shoeId: product.shoeId } })
      if (res.data.code === 200) {
        const data = res.data.data
        // 处理图片数据
        let imageUrls = []
        if (data.shoeImages && data.shoeImages.length > 0) {
          // 如果有shoeImages数组，使用其中的imageUrl
          imageUrls = data.shoeImages.map(item => item.imageUrl)
        } else if (data.imageUrl) {
          // 如果只有单个imageUrl，转换为数组
          imageUrls = [data.imageUrl]
        }
        
        this.editForm = {
          ...data,
          shoeType: data.shoeType?.typeId || null,
          brand: data.brand?.brandId || null,
          color: data.color?.colorId || null,
          releaseDate: data.releaseDate ? data.releaseDate.substr(0, 10) : '',
          imageUrls: imageUrls // 使用处理后的图片数组
        }
        this.editSizeStock = {}
        this.sizeList.forEach(size => {
          const found = data.inventoryList?.find(item => item.sizeId === size.sizeId)
          this.$set(this.editSizeStock, size.sizeId, found ? found.quantity : 0)
        })
      }
      this.editLoading = false
    },

    // 删除产品
    async handleDelete(product) {
      try {
        await this.$confirm(`确定要删除产品"${product.shoeName}"吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 这里需要调用删除接口
        // const response = await axios.post('/api/shoe/delete', { id: product.shoeId })
        
        this.$message.success('删除成功')
        this.fetchProductList()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },

    // 重置新增表单
    resetAddForm() {
      this.addForm = {
        shoeType: null,
        brand: null,
        color: null,
        serialNumber: '',
        shoeName: '',
        price: 0,
        discountedPrice: 0,
        releaseDate: '',
        origin: '',
        gender: '',
        description: '',
        totalSales: 0,
        detailInfo: '',
        points: 0,
        shoeStatus: 1,
        imageUrl: '',
        imageUrls: [] // 重置时清空多图片
      }
      this.$refs.addForm && this.$refs.addForm.resetFields()
      // 重新初始化尺寸库存
      if (this.sizeList.length > 0) {
        this.initSizeStock()
      }
    },

    // 重置编辑表单
    resetEditForm() {
      this.editForm = {
        shoeType: null,
        brand: null,
        color: null,
        serialNumber: '',
        shoeName: '',
        price: 0,
        discountedPrice: 0,
        releaseDate: '',
        origin: '',
        gender: '',
        description: '',
        totalSales: 0,
        detailInfo: '',
        points: 0,
        shoeStatus: 1,
        imageUrl: '',
        imageUrls: [] // 重置时清空多图片
      }
      this.editSizeStock = {}
      this.editShoeId = null
    },

    // 获取性别标签类型
    getGenderTagType(gender) {
      switch (gender) {
        case '男':
          return 'primary'
        case '女':
          return 'success'
        case '男女':
          return 'warning'
        default:
          return 'info'
      }
    },

    // 编辑产品
    async handleEditProduct() {
      try {
        await this.$refs.editForm.validate()
        this.editLoading = true
        
        // 构建图片数据
        const shoeImages = this.editForm.imageUrls && this.editForm.imageUrls.length > 0 
          ? this.editForm.imageUrls.map((imageUrl) => ({
              imageId: 0,
              imageUrl: imageUrl, // 直接使用文件名
              shoeId: this.editShoeId
            }))
          : []

        console.log('编辑产品时的图片数据:', this.editForm.imageUrls)
        console.log('构建的shoeImages:', shoeImages)

        const requestData = {
          brand: this.brandList.find(b => b.brandId === this.editForm.brand) || {
            brandGender: "",
            brandId: 0,
            brandName: "",
            brandRemark: "",
            brandStatus: 0
          },
          color: this.colorList.find(c => c.colorId === this.editForm.color) || {
            colorId: 0,
            colorName: "",
            colorRemark: "",
            colorStatus: 0
          },
          description: this.editForm.description,
          detailInfo: this.editForm.detailInfo,
          discountedPrice: this.editForm.discountedPrice,
          gender: this.editForm.gender,
          imageUrl: this.editForm.imageUrls.length > 0 ? this.editForm.imageUrls[0] : '',
          inventoryList: this.sizeList.map(size => ({
            quantity: this.editSizeStock[size.sizeId] || 0,
            shoeId: this.editShoeId,
            sizeId: size.sizeId
          })),
          origin: this.editForm.origin,
          points: this.editForm.points,
          price: this.editForm.price,
          releaseDate: this.editForm.releaseDate,
          serialNumber: this.editForm.serialNumber,
          shoeId: this.editShoeId,
          shoeImages: shoeImages,
          shoeName: this.editForm.shoeName,
          shoeStatus: this.editForm.shoeStatus,
          shoeType: this.typeList.find(t => t.typeId === this.editForm.shoeType) || {
            typeId: 0,
            typeName: "",
            typeRemark: "",
            typeStatus: 0
          },
          totalSales: this.editForm.totalSales
        }
        const res = await axios.post('/api/shoe/update', requestData)
        if (res.data.code === 200) {
          this.$message.success('修改成功')
          this.editDialogVisible = false
          this.fetchProductList()
        } else {
          this.$message.error(res.data.msg || '修改失败')
        }
      } catch (error) {
        if (error !== false) this.$message.error('修改失败')
      } finally {
        this.editLoading = false
      }
    },

    // 图片上传处理 (编辑弹窗)
    async handleEditImageUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt500K = file.size / 1024 < 500
      if (!isImage) {
        this.$message.error('上传文件只能是图片格式!')
        return false
      }
      if (!isLt500K) {
        this.$message.error('上传图片大小不能超过 500KB!')
        return false
      }
      try {
        const formData = new FormData()
        formData.append('flimage', file)
        const response = await axios.post('/api/uploadImage', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        if (response.data.code === 200) {
          // 只保存文件名，不保存完整URL
          this.editForm.imageUrls.push(response.data.data)
          console.log('编辑弹窗图片上传成功，当前图片数组:', this.editForm.imageUrls)
          this.$message.success('图片上传成功')
        } else {
          this.$message.error(response.data.msg || '图片上传失败')
        }
      } catch (error) {
        console.error('图片上传失败:', error)
        this.$message.error('图片上传失败')
      }
      return false
    },

    // 关闭新增弹窗
    handleCloseAddDialog() {
      this.addDialogVisible = false
      this.resetAddForm()
    },

    // 关闭编辑弹窗
    handleCloseEditDialog() {
      this.editDialogVisible = false
      this.resetEditForm()
    },

    // 移除图片
    removeImage(index, type) {
      if (type === 'add') {
        this.addForm.imageUrls.splice(index, 1)
      } else if (type === 'edit') {
        this.editForm.imageUrls.splice(index, 1)
      }
    }
  }
}
</script>

<style scoped>
.product-list-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  color: #333;
  font-size: 24px;
  margin: 0;
}

.content-card {
  background: white;
  border-radius: 10px;
  padding: 30px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.button-group {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.dialog-footer {
  text-align: right;
}

.product-name {
  font-weight: 500;
  color: #333;
}

.price {
  color: #f56c6c;
  font-weight: 500;
}

.discounted-price {
  color: #67c23a;
  font-weight: 500;
}

.no-discount {
  color: #909399;
}

.brand-name {
  color: #409eff;
}

.type-name {
  color: #606266;
}

.color-name {
  color: #606266;
}

.sales {
  color: #e6a23c;
  font-weight: 500;
}

.points {
  color: #67c23a;
  font-weight: 500;
}

.size-stock-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 10px;
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.size-stock-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.size-label {
  min-width: 80px;
  font-size: 14px;
  color: #606266;
}

.image-preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.image-preview-item {
  position: relative;
  width: 80px;
  height: 80px;
  border: 1px solid #eee;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
}

.preview-image {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-close-btn {
  position: absolute;
  top: 2px;
  right: 2px;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 10;
}

.image-close-btn:hover {
  background-color: rgba(0, 0, 0, 0.7);
}

.image-close-btn i {
  color: white;
  font-size: 12px;
}
</style>
